package com.heys1.support.sensitive.strategy;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.util.StringUtils;

@AllArgsConstructor
public enum SensitiveStrategy {
    /**
     * 中间打星
     */
    MIDDLE((str, sChar) -> {
        if (StrUtil.isBlank(str)) {
            return str;
        }
        //默认打4星
        int num = 4;
        //若长度大于一定程度，多打点
        if (str.length() > 15) {
            num = str.length() / 2;
        }

        if (str.length() <= num) {
            //长度不足，全星
            return buildSensitiveStr(str.length(), sChar);
        }
        int len = str.length();
        int middleStart = (str.length() - num) / 2;
        String left = str.substring(0, middleStart);

        //长度不足，尾部加星
        if (len - left.length() <= num) {
            return left + buildSensitiveStr(str.length() - left.length(), sChar);
        }

        //中间加星
        String right = str.substring(middleStart + num);
        return left + buildSensitiveStr(num, sChar) + right;
    }),
    /**
     * 全星
     */
    ALL((str, sChar) -> {
        if (StrUtil.isBlank(str)) {
            return str;
        }
        return buildSensitiveStr(str.length(), sChar);
    }),
    /**
     * 邮箱
     */
    EMAIL((str, sChar) -> {
        if (!Validator.isEmail(str)) {
            return str;
        }
        int i = str.indexOf("@");
        String left = str.substring(0, i);
        String right = str.substring(i);
        return MIDDLE.strategy.handle(left, sChar) + right;
    });


    @Getter
    private final ISensitiveStrategy strategy;

    public static String buildSensitiveStr(int len, String sChar) {
        sChar = StrUtil.isNotBlank(sChar) ? sChar : ISensitiveStrategy.S_CHAR;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(StringUtils.hasLength(sChar) ? sChar : ISensitiveStrategy.S_CHAR);
        }
        return sb.toString();
    }

    public static String buildSensitiveStr(int len) {
        return buildSensitiveStr(len, ISensitiveStrategy.S_CHAR);
    }
}